import Vue from 'vue'

import Cookies from 'js-cookie'
import EventBus from './utils/eventBus'

// 挂载事件总线到Vue原型
Vue.prototype.$bus = EventBus

import Element from 'element-ui'
import '@/assets/styles/element-variables.scss'

import '@/assets/styles/index.scss' // global css
import '@/assets/styles/ruoyi.scss' // ruoyi css
import '@/assets/styles/responsive.scss' // 响应式移动端样式
import App from './App'
import store from './store'
import router from './router'
import permission from './directive/permission'
import Moment from 'moment'
import { scrollBoard } from '@jiaminghi/data-view'
Vue.use(scrollBoard)

// 导入全局配置
import config, { log } from '@/config'
import api from '@/utils/api' // 导入API工具

// 确保window.baseUrl已正确设置，如果没有则使用配置中的baseApi
if (!window.baseUrl) {
    if (process.env.NODE_ENV === 'development') {
        log.warn('window.baseUrl未在config.js中设置，使用配置中的baseApi');
    }
    window.baseUrl = config.baseApi || 'https://tcmsapi.meinn.cn'; // 设置默认API地址
} else if (process.env.NODE_ENV === 'development') {
    log.info('API地址已设置为:', window.baseUrl);
}

// 将配置挂载到Vue原型和window对象上，方便全局访问
Vue.prototype.$config = config;
window.config = config;

// 将API工具挂载到Vue原型上
Vue.prototype.$api = api;

// 将安全的日志函数挂载到Vue原型
Vue.prototype.$log = log;

import draggable from "vuedraggable" //拖拽组件
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css'

// 定义全局时间戳过滤器
Vue.filter('formatDate', function (value) {
    return Moment(value).format('YYYY-MM-DD HH:mm:ss')
})
Vue.filter('formatDate1', function (value) {
    return Moment(value).format('YYYY-MM-DD ')
})
Vue.filter('formatDate2', function (value) {
    return Moment(value).format('YYYY-MM-DD HH:mm')
})

// 自定义全局过滤器
import * as filters from './filters/index'
Object.keys(filters).forEach(key => {
    Vue.filter(key, filters[key])
})
//移动端vant组件库
import Vant from 'vant';
import 'vant/lib/index.css';

import axios from 'axios'

import '@/assets/icons' // icon
import './permission' // permission control
import { getDicts } from "@/api/vadmin/system/dict/data";
import { getConfigKey } from "@/api/vadmin/system/config";
import {
    addDateRange,
    download,
    handleTree,
    handleUsersTree,
    parseTime,
    resetForm,
    selectDictLabel,
    selectDictDefault,
    selectDictLabels
} from "@/utils/ruoyi";
import Pagination from "@/components/Pagination";
// 自定义表格工具扩展
import RightToolbar from "@/components/RightToolbar"
import SmallDialog from '@/components/SmallDialog';
import DeptTree from '@/components/DeptTree';
import UsersTree from '@/components/UsersTree';
import ModelDisplay from '@/components/ModelDisplay';
import CommonIcon from '@/components/CommonIcon';
import CommonStaticTable from '@/components/CommonStaticTable';
import { getCrontabData, getIntervalData } from "./utils/validate"; // 通用图标组件

// 全局组件
import MobileSkeleton from "@/components/MobileSkeleton" // 导入骨架屏组件

// 全局方法挂载
Vue.prototype.getDicts = getDicts
Vue.prototype.getConfigKey = getConfigKey
Vue.prototype.parseTime = parseTime
Vue.prototype.resetForm = resetForm
Vue.prototype.addDateRange = addDateRange
Vue.prototype.selectDictLabel = selectDictLabel
Vue.prototype.selectDictDefault = selectDictDefault
Vue.prototype.selectDictLabels = selectDictLabels
Vue.prototype.getCrontabData = getCrontabData
Vue.prototype.getIntervalData = getIntervalData
Vue.prototype.download = download
Vue.prototype.handleTree = handleTree
Vue.prototype.handleUsersTree = handleUsersTree

Vue.prototype.hasPermi = function (values) {
    const permissions = store.getters && store.getters.permissions
    return permissions.some(permission => {
        return "*:*:*" === permission || values.includes(permission)
    })
};

Vue.prototype.msgSuccess = function (msg) {
    this.$message({ showClose: true, message: msg, type: "success" });
}

Vue.prototype.msgError = function (msg) {
    this.$message({ showClose: true, message: msg, type: "error" });
}

Vue.prototype.msgInfo = function (msg) {
    this.$message.info(msg);
}
// 自定义组件
Vue.component('small-dialog', SmallDialog);
Vue.component('dept-tree', DeptTree);
Vue.component('users-tree', UsersTree);
Vue.component('model-display', ModelDisplay);
// 全局组件挂载
Vue.component('Pagination', Pagination)
Vue.component('RightToolbar', RightToolbar)
Vue.component('common-icon', CommonIcon);
Vue.component('common-static-table', CommonStaticTable);
Vue.component('quill-editor', quillEditor);
Vue.component('draggable', draggable);
Vue.component('MobileSkeleton', MobileSkeleton) // 注册骨架屏组件
Vue.use(Vant)

Vue.use(permission)
import echarts from 'echarts'
Vue.use(echarts)
Vue.prototype.$echarts = echarts

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online! ! !
 */

Vue.use(Element, {
    size: Cookies.get('size') || 'medium' // set element-ui default size
})

Vue.config.productionTip = false
Vue.prototype.$axios = axios

// 修复Element UI中已弃用的DOMNodeInserted事件
// 通过覆盖原生addEventListener方法，拦截对DOMNodeInserted事件的监听并替换为MutationObserver
if (typeof window !== 'undefined' && window.Element) {
  const originalAddEventListener = window.Element.prototype.addEventListener;
  window.Element.prototype.addEventListener = function(type, listener, options) {
    if (type === 'DOMNodeInserted') {
      // 创建一个MutationObserver替代DOMNodeInserted事件
      const target = this;
      const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
          if (mutation.type === 'childList' && mutation.addedNodes.length) {
            // 为每个新增节点触发自定义事件
            mutation.addedNodes.forEach((node) => {
              if (node.nodeType === 1) { // 元素节点
                listener.call(target, { target: node });
              }
            });
          }
        });
      });
      // 开始观察目标节点
      observer.observe(target, { childList: true, subtree: true });
      // 存储observer引用以便可能的清理
      if (!this._mutationObservers) {
        this._mutationObservers = [];
      }
      this._mutationObservers.push(observer);
      return observer;
    } else {
      // 对于其他事件类型，使用原始方法
      return originalAddEventListener.call(this, type, listener, options);
    }
  };
}

new Vue({
    el: '#app',
    axios,
    router,
    store,
    render: h => h(App)
})